<?php
/**
* 短信类
* @package Libraries
* @author 江羿平<jyp@cjkt.com>
*/
namespace Libraries;

class SMS{
	
	
	/**
	 * 发送验证短信
	 * @param string $phone   手机号码
	 * @param string $content 发送内容
	 * @return bool
	 */
	public static function send($phone,$content){
		$config = CONFIG('sms');
		
		$post_data = array(
	        'account' => $config['account'],
	        'password' => $config['password'],
	        'content' =>$content,
	        'mobile' => $phone,
	    );		
		$url = $config['send_url'];			
	    $result=  curl_post($url,$post_data);
	    //处理返回结查，可能有网络问题造成的错误，所有用try
	    try {
	        $sms_xml = simplexml_load_string($result);
	        
	        $sms_result = (string) $sms_xml->code;
	        
	        if($sms_result==='2'){
	            return TRUE;
	        }
	        return  FALSE;
	    }catch (Exception $e){
	        return  FALSE;
	    }
	    return FALSE;
	}

	/**
	 * 发送验证码
	 */
	public static function sendIdentifyCode($phone, $type = 'reg')
	{
		$config = CONFIG('alidayu');
		require_once(SITE_PATH.'static/alidayuSdk/TopSdk.php');
		$c = new \TopClient;
		$c ->appkey = $config['appkey'] ;
		$c ->secretKey = $config['secretKey'] ;
		$req = new \AlibabaAliqinFcSmsNumSendRequest;

		$code = mt_rand(1000,9999);
		$redis = predis();
		$redis->set("SMS:{$type}:{$phone}", $code);
		$redis->expire("SMS:{$type}:{$phone}", 600);

		// 根据不同配置设置模版即signName
		$typeConfig = CONFIG("alidayu.{$type}");
		$req->setExtend("");
		$req->setSmsType("normal");
		$req->setSmsFreeSignName($typeConfig['signName']);

		$req->setSmsParam(json_encode([
			'code' => strval($code),
			'product' => $config['product']
		]));
		$req->setRecNum($phone);
		$req->setSmsTemplateCode($typeConfig['template']);
		$resp = $c ->execute($req);
		if (property_exists($resp, 'result') && $resp->result) {
			return true;
		}
		
		log_message('error', "send Identify code failed return:".var_export($resp));
		throw new \RuntimeException('send Identify code error'.var_export($resp), 1);
	}

	

	/**
	 * 发送短信验证码
	 * @param  string $type  发送类型
	 * @param  string $phone 发送的手机号码
	 * @return bool | array
	 */
	public static function code($type,$phone){
		$sms_config = CONFIG('sms');
		if(!is_mobile($phone)){
			return array('success'=>FALSE,'msg'=>$sms_config['code_error']['mobile']);
		}		
		if(!in_array($type,$sms_config['code_type'])){
			return array('success'=>FALSE,'msg'=>$sms_config['code_error']['type']);
		}
		$mcache = mcache();
		$sended_num = 1;
		$code_array = $mcache->get('SMS:'.$type.':'.$phone);
		if($code_array){			
			if($code_array['time'] + 60 > time()){
				return array('success'=>FALSE,'msg'=>$sms_config['code_error']['time']);
			}
			$sended_num = $code_array['count'] + 1;
			if($sended_num > 5){
				return array('success'=>FALSE,'msg'=>$sms_config['code_error']['max']);
			}
		}

		$sms_code = rand(100000,999999);
		$sms_code = str_replace(1989,9999,$sms_code);
     	$sms_code = str_replace(1259,9999,$sms_code);
     	$sms_code = str_replace(10086,99999,$sms_code);
     	$content = str_replace('{code}', $sms_code, $sms_config['code_tpl'][$type]);

		if(self::send($phone,$content)){
			$mcache->save('SMS:'.$type.':'.$phone,array('code'=>$sms_code,'time'=>time(),'count'=>$sended_num),3600*24);
			return array('success'=>TRUE,'msg'=>$sms_code);	
		}else{
			return array('success'=>FALSE,'msg'=>$sms_config['code_error']['fail']);
		}		

	}

	/**
	 * 验证手机验证码是否正确
	 * @param  string $type  发送类型
	 * @param  string $phone 发送的手机号码
	 * @param  string $code  验证码
	 * @return bool
	 */
	public static function verify($type,$phone,$code){
		$redis = predis();
		$code_array = $redis->get('SMS:'.$type.':'.$phone);
		if ($code_array && $code == $code_array) {
			$redis->del('SMS:'.$type.':'.$phone);

			return TRUE;
		}else{
			return FALSE;
		}
	}
}